/**
 * 
 */
package com.swfee.qinben.httpactions.base;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.ConnectException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.swfee.qinben.dto.base.BaseReqDto;
import com.swfee.qinben.dto.base.BaseRspDto;
import com.swfee.qinben.util.StreamUtils;

/**
 * @author ddr
 * 
 */
public abstract class ReqBaseAction<R extends BaseReqDto ,T extends BaseRspDto> {
	
	//http://210.51.55.151/webService/MedicalCare.CommonServices/login.asmx/CheckLogin
	public final static String HOST ="http://210.51.55.151"; //生产环境
//	public final static String HOST ="http://192.168.1.76"; //开发环境
	public final static int FORBIDDEN = 403;
	public final static int SUCCESS = 1;
	public final static int FAILED = 0;
	
	public abstract String getBaseActionUrl() ;




	protected Class<? extends BaseRspDto> defaultRspClass;
	
	public void setDefaultRspClass(Class<? extends BaseRspDto> defaultRspClass) {
		this.defaultRspClass = defaultRspClass;
		
	}

	public ReqBaseAction(){
		
	}
	
	@SuppressWarnings("unchecked")
	protected T doHttpForObject(R req,String url){
		
		String json = doHttp(req,url);
		
		Log.d("json:", json);
		try {
			return (T) jsonToBaseRspDtoByClass(json, defaultRspClass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}


	@SuppressWarnings("unchecked")
	protected List<T> doHttpForList(R req,String actionName) {
		
		String json = doHttp(req,actionName);
		Log.d("得到的json:", json);
		try {
			return (List<T>) jsonToBaseRspDtoListByClass(json, defaultRspClass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	protected List<? extends BaseRspDto> doHttpForList(BaseReqDto req,String actionName,Class<? extends BaseRspDto> clazz) {
		
		String json = doHttp(req,actionName);
		Log.d("得到的json:", json);
		try {
			return jsonToBaseRspDtoListByClass(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	protected BaseRspDto doHttpForObject(BaseReqDto req,String actionName,Class<? extends BaseRspDto> clazz){
		
		String json = doHttp(req,actionName);
		Log.d("得到的json:", json);
		try {
			return  jsonToBaseRspDtoByClass(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	


	
	protected String doHttp(BaseReqDto req,String actionName) {

		
		try {
			Log.d("actionName", "Action:" + actionName);
			HttpPost post = new HttpPost(HOST+getBaseActionUrl()+ actionName);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();

			StringBuffer cc = new StringBuffer();
			
		
			String[] pairs = req.propsToUrl().split("&");
			for (int i = 0; i < pairs.length; i++) {
				String[] keyvalue = pairs[i].split("=");
				String value = "";
				if (keyvalue.length > 1) {
					value = keyvalue[1];
				}
//				Log.d("mytag", keyvalue[0] + "=" + value);
				if (i != 0) {
					cc.append("&" + keyvalue[0] + "="
							+ URLEncoder.encode(value, BaseReqDto.ENCODING));
					// cc.append("&" + keyvalue[0] + "=" + value);
				} else {
					cc.append(keyvalue[0] + "="
							+ URLEncoder.encode(value, BaseReqDto.ENCODING));
					// cc.append(keyvalue[0] + "=" + value);
				}
				nvps.add(new BasicNameValuePair(keyvalue[0], value));
			}
			Log.d("props", "编码后的请求：" + cc.toString());
			
		
			HttpClient client = new DefaultHttpClient();
			post.setEntity(new UrlEncodedFormEntity(nvps, BaseReqDto.ENCODING));
			HttpResponse response = null;
			try {
				response = client.execute(post);
			} catch (ConnectException e) {
				e.printStackTrace();
				return "提交服务器连接异常";
			}

			String data = "";
				// 响应数据
				HttpEntity httpEntity = response.getEntity();
				if (httpEntity != null) {
					InputStream inputStream = httpEntity.getContent();
					data = StreamUtils.convertStreamToString(inputStream);
					return data;
				}
			
		} catch (Exception e) {
			e.printStackTrace();
			return "其它异常";
		}

		return "其它未知异常";

	}
	
	
	private  BaseRspDto jsonToBaseRspDtoByClass(String json,Class<? extends BaseRspDto> clazz) throws Exception{
		
		
		
		JSONObject jsonObj = new JSONObject(json);
		BaseRspDto dto = getRspDtoByClass(clazz);
		Field[] fieldTps = dto.getClass().getDeclaredFields();
		
		for (Field fdTp : fieldTps) {
			String tpName = fdTp.getName();
			fdTp.setAccessible(true);
			Object value1 =  jsonObj.get(tpName);
			if(value1!=null && !value1.toString().equals("null")){
				fdTp.set(dto, value1);
			}
		}
		dto.setReqStatus(true);
		return dto;
	}
	
	private  List<BaseRspDto> jsonToBaseRspDtoListByClass(String json,Class<? extends BaseRspDto> clazz) throws Exception{
		
		JSONArray jsonArray = new JSONArray(json);
		List<BaseRspDto> list = new ArrayList<BaseRspDto>();
		for(int i=0;i<jsonArray.length();i++){
			BaseRspDto dto = getRspDtoByClass(clazz);
			Field[] fieldTps = dto.getClass().getDeclaredFields();
			JSONObject jsonObj = jsonArray.getJSONObject(i);
			for (Field fdTp : fieldTps) {
				if(fdTp.getModifiers()==25){ //public static final 
					continue ;
				}
				String tpName = fdTp.getName();
				fdTp.setAccessible(true);
				if(jsonObj.isNull(tpName)){
					continue;
				}
				Object value1 =  jsonObj.get(tpName);
				if(value1 == null ||  value1.toString().equals("null")){
					continue;
				}
				fdTp.set(dto, value1);
			}
			dto.setReqStatus(true);
			list.add(dto);
		}
		return list;
	}
	

	
	@SuppressWarnings("unchecked")
	private BaseRspDto getRspDtoByClass(Class<? extends BaseRspDto > clazz) {
		try {
			Class<? extends BaseRspDto > c  = (Class<? extends BaseRspDto >) Class.forName(clazz.getName());
			BaseRspDto o =   c.newInstance();
			return o;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
//	public String doGet() {
//	    //先将参数放入List，再对参数进行URL编码  
//	    List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();  
//	    params.add(new BasicNameValuePair("loginName", "1112"));  
//	    params.add(new BasicNameValuePair("password", "2222"));  
//	      
//	    //对参数编码  
//	    String param = URLEncodedUtils.format(params, "UTF-8");  
//	      
//	    //baseUrl             
//	    String baseUrl = "http://210.51.55.151/webService/MedicalCare.CommonServices/login.asmx/CheckLogin";  
//	      
//	    //将URL与参数拼接  
//	    HttpGet getMethod = new HttpGet(baseUrl + "?" + param);  
//	                  
//	    HttpClient httpClient = new DefaultHttpClient();  
//	      
//	    try {  
//	        HttpResponse response = httpClient.execute(getMethod); //发起GET请求  
//	    	InputStream inputStream = response.getEntity().getContent();
//			String data = StreamUtils.convertStreamToString(inputStream);
//			System.out.println(data);
//	        
//	    } catch (ClientProtocolException e) {  
//	        e.printStackTrace();  
//	    } catch (IOException e) {  
//	        e.printStackTrace();  
//	    }  
//	    return "";
//	}
//	
	
//	public String doPost(){
//		
//		DefaultHttpClient httpClient = new DefaultHttpClient();  
//        String soapRequestData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +  
//        "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"  +  
//          "<soap12:Body>" +  
//           " <CheckLogin  xmlns=\"http://tempuri.org/\">" +  
//             "<loginName>dddddr</loginName>" +  
//            "<password>111111</password>" +  
//            "</CheckLogin>" +  
//         " </soap12:Body>" +  
//        "</soap12:Envelope>" ;  
//          
//        HttpPost httppost = new HttpPost("http://210.51.55.151/webService/MedicalCare.CommonServices/login.asmx");  
//        /*把Soap请求数据添加到PostMethod*/  
//        //byte[] b = soapRequestData.getBytes("utf-8");  
//        //InputStream is = new ByteArrayInputStream(b,0,b.length);  
//        try {  
//            HttpEntity re = new StringEntity(soapRequestData,HTTP.UTF_8);  
//            httppost.setHeader("Content-Type","application/soap+xml; charset=utf-8");  
////            httppost.setHeader("Content-Length", String.valueOf(soapRequestData.length()));  
//            httppost.setEntity(re);           
//            HttpResponse response = httpClient.execute(httppost);  
//            String str = EntityUtils.toString(httppost.getEntity());
//            System.out.println(EntityUtils.toString(httppost.getEntity()));  
//            System.out.println(response.getStatusLine());  
//            System.out.println(EntityUtils.toString(response.getEntity()));  
//           
//        } catch (UnsupportedEncodingException e) {  
//            e.printStackTrace();  
//        } catch (ClientProtocolException e) {  
//            e.printStackTrace();  
//        } catch (IOException e) {  
//            e.printStackTrace();  
//        }finally{  
//            httpClient.getConnectionManager().shutdown();  
//        }
//		return soapRequestData;  
//          
//    }  
//	
	

}
